import { useDebounceFn } from '@vueuse/core'
import { computed, ref } from 'vue'
import message from '@/components/common/message'
import { resetPassword, verifyCode } from '@/request/auth'
import { joinClassByInviteCode } from '@/request/teacher/class'
import { useTeacherStore } from '@/store/teacher'

export function useIndividualSettings() {
  const teacherStore = useTeacherStore()

  // Form data refs
  const personalInfo = ref({
    name: '',
    phone: '',
    school: '',
    stageType: 0,
    gender: '',
    birthday: new Date(),
  })

  const invitationCode = ref('')
  const passwordReset = ref({
    phone: '',
    verificationCode: '',
    newPassword: '',
  })

  const isLoading = ref(false)
  const isCodeSent = ref(false)

  const countdown = ref(0)
  // Countdown for verification code
  const startCountdown = () => {
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  // Initialize form with teacher data
  const initializeForm = () => {
    const teacher = teacherStore.teacher
    personalInfo.value = {
      name: teacher.name,
      phone: teacher.phone,
      school: teacher.school,
      stageType: teacher.stageType,
      gender: teacher.gender,
      birthday: new Date(teacher.birthday),
    }
  }

  // Update personal info
  const updatePersonalInfo = useDebounceFn(async () => {
    try {
      isLoading.value = true
      await teacherStore.updateInfo({
        birthday: personalInfo.value.birthday.toISOString(),
        gender: personalInfo.value.gender,
        name: personalInfo.value.name,
        phone: personalInfo.value.phone,
        school: personalInfo.value.school,
        stageType: personalInfo.value.stageType,
      })
      message.success('个人信息更新成功')
    }
    catch {
      message.error('更新失败')
    }
    finally {
      isLoading.value = false
    }
  }, 400)

  // Verify invitation code
  const verifyInvitationCode = async () => {
    if (!invitationCode.value.trim()) {
      message.error('请输入邀请码')
      return
    }

    try {
      isLoading.value = true
      await joinClassByInviteCode({ invitationCode: invitationCode.value })
      message.success('加入班级成功')
      invitationCode.value = ''
    }
    catch {
      message.error('邀请码验证失败')
    }
    finally {
      isLoading.value = false
    }
  }

  // Send verification code
  const sendVerificationCode = useDebounceFn(async () => {
    if (!passwordReset.value.phone.trim()) {
      message.error('请输入手机号')
      return
    }

    try {
      isLoading.value = true
      await verifyCode({ data: passwordReset.value.phone })
      message.success('验证码已发送')
      isCodeSent.value = true
      startCountdown()
    }
    catch {
      message.error('发送验证码失败')
    }
    finally {
      isLoading.value = false
    }
  }, 400)

  // Reset password
  const resetUserPassword = useDebounceFn(async () => {
    if (!passwordReset.value.phone || !passwordReset.value.verificationCode || !passwordReset.value.newPassword) {
      message.error('请填写完整信息')
      return
    }

    try {
      isLoading.value = true
      await resetPassword({
        phoneNumber: passwordReset.value.phone,
        verificationCode: passwordReset.value.verificationCode,
        password: passwordReset.value.newPassword,
      })
      message.success('密码重置成功')
      passwordReset.value = { phone: '', verificationCode: '', newPassword: '' }
      isCodeSent.value = false
    }
    catch {
      message.error('密码重置失败')
    }
    finally {
      isLoading.value = false
    }
  }, 400)

  const canSendCode = computed(() => countdown.value <= 0 && !isLoading.value)
  const sendCodeButtonText = computed(() =>
    countdown.value > 0 ? `${countdown.value}s后重新发送` : '发送验证码',
  )

  // Stage type options
  const stageTypeOptions = [
    { label: '小学', value: 1 },
    { label: '初中', value: 2 },
    { label: '高中', value: 3 },
  ]

  return {
    personalInfo,
    invitationCode,
    passwordReset,
    isLoading,
    isCodeSent,
    canSendCode,
    sendCodeButtonText,
    stageTypeOptions,
    initializeForm,
    updatePersonalInfo,
    verifyInvitationCode,
    sendVerificationCode,
    resetUserPassword,
  }
}
